import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { Input, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useState } from 'react';
import { connect } from 'react-redux';
import './index.scss';

const GiftCardBind = ({ dispatch, loading }) => {
  const isLoading = useShowLoading(loading, ['giftCard/bindGiftCard']);

  const [cardValues, setCardValues] = useState({});

  const handleChange = (no, pwd) => {
    if (no) {
      setCardValues({
        ...cardValues,
        no,
      });
    }

    if (pwd) {
      setCardValues({
        ...cardValues,
        pwd,
      });
    }
  };

  const bindCard = async () => {
    if (isLoading) {
      return;
    }

    if (!cardValues.no) {
      Taro.showToast({
        title: '请输入券号',
        duration: 1000,
        icon: 'none',
      });
      return;
    }

    await dispatch({
      type: 'giftCard/bindGiftCard',
      payload: {
        cardMark: cardValues.no,
        secretKey: cardValues.pwd?.replace(/-/g, ''),
      },
    });

    await Taro.showToast({
      title: '绑定成功',
      duration: 1000,
      icon: 'none',
    });

    await new Promise((resolve) => {
      setTimeout(resolve, 1000);
    });

    setCardValues({});

    await Taro.navigateTo({ url: '/giftCardSubPack/myGiftCard/index' });
  };

  return (
    <View className="giftCardBind">
      <View className="bind-title">输入券号密码</View>

      <View className="bind-form">
        <View className="bind-card-input-wrap">
          <View className="bind-card-label">券号</View>
          <Input
            className="bind-card-input"
            placeholderClass="bind-card-input-placeholder"
            value={cardValues?.no}
            type="text"
            placeholder="请输入提货券券号"
            onInput={(e) => {
              let v = e?.detail?.value;

              handleChange(v);
            }}
          />
        </View>
        <View className="bind-card-input-wrap">
          <View className="bind-card-label">密码</View>

          <Input
            className="bind-card-input"
            placeholderClass="bind-card-input-placeholder"
            type="password"
            placeholder="请输入提货券密码"
            value={cardValues?.pwd}
            onInput={(e) => {
              let v = e?.detail?.value;
              handleChange(undefined, v);
            }}
          />
        </View>

        <View
          className={classNames('bind-button customePageBackgroundStyle', { disabled: isLoading })}
          onClick={bindCard}
        >
          <View className="button-text">立即绑定</View>
        </View>
      </View>
    </View>
  );
};
export default connect(({ loading }) => ({
  loading,
}))(GiftCardBind);
